import React, { useEffect,useState} from 'react';
import { Modal, Form, Input, Select, Cascader, Upload, Button, Row, Col ,message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { FormItemConfig,DynamicFormModalProps} from './types';
import {FetchService} from "@/utils/request";
const { Option } = Select;
const { TextArea } = Input;
const fetchService = new FetchService();
const DynamicFormModal: React.FC<DynamicFormModalProps> = ({
  visible,
  title,
  formData,
  onCancel,
  modalWidth,
  formConfig,
  onSave,
  onChange,
}) => {
  const [form] = Form.useForm();
  const [uploading, setUploading] = useState(false); // 上传状态
  // 监听 formData 变化，设置表单初始值
  useEffect(() => {
    if (formData) {
      form.setFieldsValue(formData);
    } else {
      form.resetFields(); // 如果没有 formData，清空表单
    }
  }, [formData, form]);

  // 监听表单变化
  const handleFormChange = (changedValues:any, allValues: any) => {
    onChange(changedValues, allValues);
  };

  // 提交表单
  const handleSave = () => {
    form
      .validateFields()
      .then((values: any) => {
        onSave(values);
        form.resetFields();
      })
      .catch((error) => {
        console.error('表单验证失败:', error);
      });
  };
  // 自定义上传逻辑
  const handleUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;

    setUploading(true); // 开始上传

    const formData = new FormData();
    console.log('file:', file);
    formData.append('file', file);

    try {
      // 调用上传接口
      const response:any = await fetchService.form('/uploads', formData);

      // 上传成功
      onSuccess(response.data.url, file); // 假设服务器返回 { url: "图片地址" }
      message.success('上传成功');

      // 将图片 URL 设置到表单中
      const imageField = formConfig.find((item) => item.component === 'upload')?.key;
      if (imageField) {
        form.setFieldsValue({ [imageField]: response.data.path });
      }
    } catch (error) {
      // 上传失败
      onError(error);
      message.error('上传失败');
    } finally {
      setUploading(false); // 结束上传
    }
  };

  const itemChange = (changedValues: any, allValues: any) => {
    handleFormChange(changedValues, allValues);
  };

  // 动态渲染表单项
  const renderFormItem = (item: FormItemConfig) => {
    switch (item.component) {
      case 'input':
        return <Input  allowClear={true} disabled={item.disabled} placeholder={`请输入${item.name}`} />;
      case 'textarea':
        return <TextArea disabled={item.disabled} placeholder={`请输入${item.name}`} />;
      case 'select':
        return (
          <Select disabled={item.disabled} allowClear={true}  placeholder={`请选择${item.name}`}>
            {item.items?.map((option) => (
              <Option key={option.value} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        );
      case 'cascader':
        return <Cascader disabled={item.disabled} allowClear={true}  placeholder={`请选择${item.name}`} options={item.items} />;
      case 'upload':
        return (
          <Upload
            disabled={item.disabled}
            customRequest={handleUpload} // 自定义上传逻辑
            listType="picture" // 显示图片预览
            defaultFileList={
              formData?.[item.key]
                ? [{ uid: '-1', name: '已上传图片', url: formData[item.key] as string }]
                : []
            } // 回显已上传的图片
          >
            <Button icon={<UploadOutlined />} loading={uploading}>
              上传图片
            </Button>
          </Upload>
          // <Upload >
          //   <Button icon={<UploadOutlined />}>上传文件</Button>
          // </Upload>
        );
      default:
        return null;
    }
  };

  return (
    <Modal
      title={title}
      visible={visible}
      onCancel={onCancel}
      onOk={handleSave}
      destroyOnClose
      width={modalWidth}
    >
      <Form form={form} onValuesChange={handleFormChange} layout="vertical">
        <Row gutter={16}> {/* 设置列间距 */}
          {formConfig.map((item) => (
            <Col span={item.span || 24} key={item.key}> {/* 默认占满 24 列 */}
              <Form.Item
                name={item.key}
                label={item.name}
                rules={[{ required: item.required, message: `请输入${item.name}` }]}
              >
                {renderFormItem(item)}
              </Form.Item>
            </Col>
          ))}
        </Row>
      </Form>
    </Modal>
  );
};

export default DynamicFormModal;